<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\CurrencyLog;
use App\Models\Entrust;
use App\Models\Order;
use App\Models\Slide;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{
    /**
     * 首页 web页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $btc = (new CurrencyLog())->get_index_socket_data();

        return ['status'=>1,'msg'=>'成功','data'=>$btc];
        //banner图
//        $banner = Slide::select('title', 'img', 'webpage', 'created_at', 'updated_at')->where('del', 1)->limit(3)->orderBy('order', 'DESC')->get()->toArray();
//        foreach ($banner as $key=>$item){
//            $banner[$key]['webpage'] = empty($item['webpage']) ? 'javascript:void(0);': $item['webpage'];
//        }
//        return view('api/index/index', compact('btc', 'banner'));
    }

    /**
     * 首页行情二级WEB页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index_market(Request $request)
    {
        $btc = (new CurrencyLog())->get_index_market_data();

        return view('api/index/index_market', compact('btc'));
    }

    /**
     * K线图
     * @date 2018/03/19
     * @author yanggang
     * @param Request $request
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index_kline(Request $request)
    {
        $id = $request->get('id');//币种ID
        /**
         * 时间区间 默认为1天  1 1分钟，2 5分钟， 3 15分钟， 4 30分钟， 5 1小时， 6 4小时，7 5天， 8 7天， 9 30天
         * 1分钟   查前5个小时的数据
         * 5分钟   查前25个小时的数据
         * 15分钟  查前75个小时的数据
         * 30分钟  查前150个小时的数据
         * 1小时   查前297个小时的数据
         * 4小时   查前1200个小时的数据
         * 1天     查前144天的数据
         * 1天以上 查全部的数据
         */
        $time_type = $request->get('time_type') ?? 0;

        if (empty($id)) {
            return respF(1003);
        }

        $name_en = Currency::where(['id'=>$id])->value('name_en');

        return view('api/index/index_kline', compact('id','time_type','name_en'));
    }

    /**
     * K线图头部
     * @date 2018/03/19
     * @author yanggang
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index_kline_head(Request $request)
    {
        $id = $request->get('id'); //币种id

        if (empty($id)) {
            return ['status' => 0, 'msg' => '缺少参数'];
        }

        $list =Currency::where(['id'=>$id])->first();

        if(!$list){
            return ['status' => 0, 'msg' => '币种不存在'];

        }
        $open_price = (new CurrencyLog())->getOpenPrice($id);

        $orders = Order::where(['cid' => $id,'type'=>1])->orderBy('id', 'DESC')->get();
        //最高价
        $max_price = $orders->max('price') ?? $list['official_price'];
        //最低价
        $min_price = $orders->min('price') ?? $list['official_price'];
        //成交总价
        $sum_price = $orders->sum('total_price') ?? $list['official_price'];
        //成交总量
        $order_count = $orders->sum('num');
        //最新价
        $lasted_order = $orders->first();
        $lasted_price = $lasted_order['price'] ??$list['official_price'];
//
        //买一卖一
        $time = strtotime(date('Y-m-d'));
        $buy_first_price = Entrust::where(['cid' => $id, 'type' => 3])
            ->whereIn('status',[1,2])
            ->max('price'); //买一
        if (!$buy_first_price) {
            $buy_first_price = 0;
        }

        $sale_first_price = Entrust::where(['cid' => $id, 'type' => 4])
            ->whereIn('status',[1,2])
            ->min('price'); //卖一
        if (!$sale_first_price) {
            $sale_first_price = 0;
        }

        $close_price = (new CurrencyLog())->get_last_close_price($id);
        //涨幅
        $gains_data = $this->get_gains($close_price,$lasted_price);
        $gains = $gains_data['gains'];
        $gains_type = $gains_data['gains_type'];
        //振幅
//        $today_orders = (new CurrencyLog())::where(['cid' => $id, 'time' => $time])->get();
//        if (!$today_orders || !$close_price) {
//            $swing = '0%';
//        } else {
//            $today_max_price = $today_orders->max('high_price');
//            $today_min_price = $today_orders->min('lower_price');
//            $swing = number_format(($today_max_price - $today_min_price) / $close_price*100, 2) . '%';
//        }
        if($order_count < 10000){
            $order_count = intval(round($order_count));
        }else{
            $order_count = price_format($order_count/10000).'万';
        }
        $currency_list = Currency::where(['id' => $id])->first();
        $data = [
            'open_price' => '$'.price_format($open_price),
//            'close_price' => '$'.price_format($close_price),
            'name' => $currency_list['name'],
            'name_en' => $currency_list['name_en'],
            'lasted_price' => '$'.price_format($lasted_price),
            'max_price' => '$'.price_format($max_price),
            'min_price' => '$'.price_format($min_price),
            'buy_price' => '$'.price_format($buy_first_price),
            'sale_price' => '$'.price_format($sale_first_price),
            'gains' => $gains,
            'gains_type' => $gains_type,
//            'swing' => $swing,
            'order_count' => $order_count,
            'buy_fee' => number_format($currency_list['fee'],2).'%',
            'time' => date('H:i:s'),
        ];

        $list = [
            'status' => 1,
            'msg' => '成功',
            'data' => $data
        ];
        return response()->json($list);
    }

    /**
     * 深度图
     * @date 2018/03/21
     * @author yanggang
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function depth_line(Request $request)
    {
        $id = $request->get('id');

        if (empty($id)) {
            return respF(1003);
        }

        return view('api/index/depth_line',compact('id'));


    }

    /**
     * K线图竖屏
     * @date 2018/03/26
     * @author yanggang
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index_kline_h(Request $request)
    {
        /**
         * 时间区间 默认为1天  1 1分钟，2 5分钟， 3 15分钟， 4 30分钟， 5 1小时， 6 4小时，7 5天， 8 7天， 9 30天
         * 1分钟   查前5个小时的数据
         * 5分钟   查前25个小时的数据
         * 15分钟  查前75个小时的数据
         * 30分钟  查前150个小时的数据
         * 1小时   查前297个小时的数据
         * 4小时   查前1200个小时的数据
         * 1天     查前144天的数据
         * 1天以上 查全部的数据
         */
        $id = $request->get('id');
        $time_type = $request->get('time_type') ?? 0;

        if (empty($id)) {
            return ['status' => 0, 'msg' => '缺少参数'];
        }

        $name_en = Currency::where(['id'=>$id])->value('name_en');

        return view('api/index/index_kline_h', compact('data','id','time_type','name_en'));
    }

    /**
     * 获取k线图数据
     * @author yanggang
     * @date 2018/04/03
     * @param Request $request
     * @return array
     */
    public function index_kline_data(Request $request)
    {
        $id = $request->get('id');//币种ID
        /**
         * 时间区间 默认为1天  1 1分钟，2 5分钟， 3 15分钟， 4 30分钟， 5 1小时， 6 4小时，7 5天， 8 7天， 9 30天
         * 1分钟   查前5个小时的数据
         * 5分钟   查前25个小时的数据
         * 15分钟  查前75个小时的数据
         * 30分钟  查前150个小时的数据
         * 1小时   查前297个小时的数据
         * 4小时   查前1200个小时的数据
         * 1天     查前144天的数据
         * 1天以上 查全部的数据
         */
        $time_type = $request->get('time_type') ?? 0;
        $page = $request->get('page') ?? 1;

        if (empty($id)) {
            return respF(1003);
        }

        if(!(new Currency())->where(['id'=>$id])->first()) {
            return respF(1007);
        }

        $res = (new CurrencyLog())->get_kline_new($id,$time_type,$page);
        $list = [
            'status'=>1,
            'msg'=>'成功',
            'data'=>[
                'id'=>$id,
                'time_type'=>$time_type,
                'data'=>$res
            ]
        ];

        return $list;
    }

    /**
     * 深度图数据
     * @date 2018/04/03
     * @author yanggang
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function depth_line_data(Request $request)
    {
        $id = $request->get('id');

        if (empty($id)) {
            return respF(1003);
        }

        if(!(new Currency())->where(['id'=>$id])->first()) {
            return respF(1007);

        }

        $buy = Entrust::select(DB::raw('price,( sum(num)-sum(deal) ) as t_num'))
            ->where(['cid'=>$id,'type'=>3])
            ->whereIn('status',[1,2])
            ->groupBy('price')
            ->orderBy('price','DESC')
            ->limit(20)
            ->get()->toArray();

        $sale = Entrust::select(DB::raw('price,( sum(num)-sum(deal) ) as t_num'))
            ->where(['cid'=>$id,'type'=>4])
            ->whereIn('status',[1,2])
            ->groupBy('price')
            ->orderBy('price','ASC')
            ->limit(20)
            ->get()->toArray();

        $buy = array_reverse($buy);
        $num_buy = [];
        $num_sale = [];
        $price_buy = [];
        $price_sale = [];

        foreach ($buy as $item) {
            $num_buy[] = $item['t_num'];
            array_push($price_buy,price_format($item['price']));
        }

        foreach ($sale as $item) {
            $num_sale[] = $item['t_num'];
            array_push($price_sale,price_format($item['price']));
        }

        //虚拟数组
        $fake_arr = [];
        if ($buy && $sale) {
            $buy_high = $price_buy[count($price_buy)-1];
            $sale_lower = $price_sale[0];
            $price_spread  = $sale_lower- $buy_high;//中间差价
            $fake_price = number_format($price_spread / 5,2,'.','');

            for ($i=1;$i<5;$i++) {
                $fake_arr[] = $buy_high + $fake_price*$i;
                $num_buy[] = 0;
            }
        }

        $num_arr =  array_merge($num_buy,$num_sale);
        $list = [
            'status'=>1,
            'msg'=>'成功',
            'data'=>[
                'buy'=>$price_buy,
                'sale'=>$price_sale,
                'fake'=>$fake_arr,
                'num'=>$num_arr
            ]
        ];

        return $list;
    }

    /**
     * 获取oba的昨日收盘价
     * @author: yanggang
     * @date: 2018/4/19 0019
     * @return array
     */
    public function get_currency_close_price()
    {
        $id = (new Currency())->where(['name_en'=>'oba'])->value('id');

        if (!$id) {
            return respF(1003);
        }
        $close_price = price_format((new CurrencyLog())->get_last_close_price($id));
        
        return ['status'=>1,'msg'=>'成功','data'=>['close'=>$close_price]];
    }

    /**
     * 计算币种涨幅
     * @author: yanggang
     * @date: 2018/5/21 0021
     * @param $close_price 收盘价
     * @param $lasted_price 最新价
     * @return array
     */
    public function get_gains($close_price,$lasted_price)
    {
        $gains_type = 0 ; //默认绿色
        if (!$close_price || !$lasted_price) {
            $gains = '+0.00%';
        } else {
            $gains = price_format(($lasted_price - $close_price) / $close_price*100);
            if ($gains*1 < 0){
                $gains_type = 1; //红色
                $gains = $gains.'%';
            }else{
                $gains = '+'.$gains.'%';
            }
        }

        return ['gains'=>$gains,'gains_type'=>$gains_type];
    }
}